<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/10/14
 * Time: 14:53
 */

namespace app\api\controller;
use think\Db;
use think\Request;
use think\Cache;
class Login extends Nocommon
{
    /*
     * 账号登录接口
     */
    public function passwordLogin()
    {
        if (Request::instance()->isPost()) {
            $post = Request::instance()->post();
            //检查手机号是否存在
            $checkTel = Db::name('user')->where("phone", $post['phone'])->find();
            if ($checkTel) {
                if($checkTel['is_del']==1){
                    $this->apiReturn('400', '该账号已被冻结,如有疑问请联系客服');
                }
                //检查密码是否正确
                $hasher = new \PasswordHash(8, false);
                if ($hasher->CheckPassword($post['password'], $checkTel['password'])) {
                    //生成token
                    $user_token = md5(uniqid(md5(microtime(true)), true));
                    //将用户token更新
                    Db::name('user')->where("uid", $checkTel['uid'])->setField('token', $user_token);
                    $this->apiReturn('200', '登录成功', array('token' => $user_token, 'uid' => $checkTel['uid'], 'status' => $checkTel['status']));
                } else {
                    $this->apiReturn('401', '密码错误');
                }
            } else {
                $this->apiReturn('403', '手机号或密码不正确');
            }
        }
    }

    /*
     * 注册接口
     */
    public function register()
    {
        if (Request::instance()->isPost()) {
            $post = Request::instance()->post();
            //查看该手机是否被注册过
            $isRegister = Db::name('user')->where('phone', $post['phone'])->find();
            if ($isRegister) $this->apiReturn('400', '该手机号已经注册过');
            //查看验证码是否正确
            $cache_name = "jsms_" . $post['phone'];
            $msg_id = Cache::get($cache_name);
            if (!$msg_id) {
                $this->apiReturn('400', '短信验证码错误');

            } else {
                $res = checkJsmsCode($msg_id, $post['code']);
                if ($res['http_code'] === 200) {
                    Cache::rm($cache_name);
                } else {
                    $this->apiReturn('400', '短信验证码错误');
                }
            }
            //加密方式
            $hasher = new \PasswordHash(8, false);
            //将密码进行哈希，结果是一个长度为60个字符的字符串
            $repassword = $hasher->HashPassword($post['password']);
            //生成一个随机的昵称
            $nickname = randomkeys(8);
            $post['password'] = $repassword;
            $post['nickname'] = $nickname;
            $post['create_time'] = date('Y-m-d H:i:s');
            unset($post['code']);
            $data = [
                'phone'=>$post['phone'],
                'password'=>$repassword,
                'nickname'=>$nickname,
                'create_time'=>date('Y-m-d H:i:s')
            ];
            $insert = Db::name('user')->insertGetId($data);
            if ($insert) {
                //生成token
                $user_token = md5(uniqid(md5(microtime(true)), true));
                //将用户token更新
                $tokens = Db::name('user')->where("uid", $insert)->setField('token', $user_token);

                if (empty($tokens)) {
                    $this->apiReturn('400', 'token更新失败');
                }
                $this->apiReturn('200', '注册成功', array('token' => $user_token, 'uid' => $insert));
            } else {
                $this->apiReturn('400', '注册失败');
            }
        }
    }

    /*
     * 获取短信验证码接口
     */
    public function getCode()
    {
        if (Request::instance()->isPost()) {
            $post = Request::instance()->post();
            $response = sendJsmsCode($post['phone'], null, 1);

            if ($response['http_code'] == '200') {
                $cache_name = "jsms_" . $post['phone'];
                Cache::set($cache_name, $response['body']['msg_id'], 1000);
                $this->apiReturn('200', '发送成功');
            } else {
                $this->apiReturn('400', '发送失败');
            }

        }
    }

    /*
    * 找回密码
    */
    public function forget_password()
    {
        //获取客户端传过来的信息
        $phone = input('phone', '', 'trim');
        $code = input('code', '', 'trim');
        if (empty($phone) || empty($code)) {
            return json(array('code' => '400', 'msg' => '信息不能为空'));
        }
        //判断验证码是否正确
        $cache_name = "jsms_" . $phone;
        $msg_id = Cache::get($cache_name);
        if (!$msg_id) {
            $this->apiReturn('400', '短信验证码错误');

        } else {
            $res = checkJsmsCode($msg_id, $code);
            if ($res['http_code'] === 200) {
                Cache::rm($cache_name);
            } else {
                $this->apiReturn('400', '短信验证码错误');
            }
        }
        //查询手机号是否存在
        $res = Db::name('user')->where('phone', $phone)->find();
        if ($res) {

            return json(array('code' => '200', 'msg' => '成功', 'data' => array('phone' => $phone)));
        } else {
            return json(array('code' => '400', 'msg' => '不存在改手机号，请确认'));
        }
    }

    /*
     * 修改密码
     */
    public function update_password()
    {
        //获取客户端传过来的信息
        $password = input('password', '', 'trim');
        $repassword = input('repassword', '', 'trim');
        $phone = input('phone', '', 'trim');
        if (empty($password) || empty($repassword) || empty($phone)) {
            return json(array('code' => '400', 'msg' => '信息不能为空'));
        }
        //判断二次密码是否一致
        if ($password != $repassword) {
            return json(array('code' => '400', 'msg' => '两次密码不一致'));
        }
         //判断旧密码是否输入正确
        $checkTel = Db::name('user')->field('password,uid')->where('phone',$phone)->find();
        //旧密码加密
        if ($checkTel) {
            //检查密码是否正确
            $hasher = new \PasswordHash(8, false);
            if ($hasher->CheckPassword($password, $checkTel['password'])) {
                
                return json(array('code' => '400', 'msg' => '与原密码相同'));
            } else {
                //加密方式
                $hasher = new \PasswordHash(8, false);
                //将密码进行哈希，结果是一个长度为60个字符的字符串
                $repass = $hasher->HashPassword($password);

                $data = [
                    'password' => $repass,
                ];
                $update = Db::name('user')->where('uid', $checkTel['uid'])->update($data);
                if ($update) {
                    return json(array('code' => '200', 'msg' => '修改密码成功'));
                } else {
                    return json(array('code' => '200', 'msg' => '修改密码失败'));
                }
            }
        }else{
            return json(array('code' => '400', 'msg' => '用户不存在'));
        }
    }

    /*
        修改密码
    */

    public function edit_password()
    {
        $ord_password = input('ord_password','','trim');
        $password = input('password','','trim');
        $repassword = input('repassword','','trim');
        $post = Request::instance()->post();
        if (empty($ord_password) || empty($password) || empty($repassword)) {
            return json(array('code' => '400', 'msg' => '信息不能为空'));
        }
          //判断二次密码是否一致
        if ($password != $repassword) {
            return json(array('code' => '400', 'msg' => '两次密码不一致'));
        }
          //判断旧密码是否输入正确
        $checkTel = Db::name('user')->field('password')->where('uid',$post['uid'])->find();
         if ($checkTel) {
            //检查密码是否正确
            $hasher = new \PasswordHash(8, false);
            if ($hasher->CheckPassword($ord_password, $checkTel['password'])) {
                  //加密方式
                $hasher = new \PasswordHash(8, false);
                //将密码进行哈希，结果是一个长度为60个字符的字符串
                $repass = $hasher->HashPassword($password);

                $data = [
                    'password' => $repass,
                ];
                $update = Db::name('user')->where('uid', $post['uid'])->update($data);
                if ($update) {
                    return json(array('code' => '200', 'msg' => '修改密码成功'));
                } else {
                    return json(array('code' => '200', 'msg' => '修改密码失败'));
                }
              
            } else {
                return json(array('code' => '400', 'msg' => '原密码输入错误'));
            }
        }else{
            return json(array('code' => '400', 'msg' => '用户不存在'));
        }
    }
    /*
     * 绑定手机号接口
     */
    public function bind_phone()
    {
        if (Request::instance()->isPost()) {
            $post = Request::instance()->post();
            //获取当前的手机号
            $res = Db::name('user')->field('phone')->where('uid', $post['uid'])->find();
            if ($res) {
                $this->apiReturn('200', '成功', $res);
            }
        }
    }

    /*
     * 安全验证页面
     */
    public function anquan()
    {
        if(Request::instance()->isPost()){
            $post = Request::instance()->post();
            //判断验证码是否正确
            $cache_name = "jsms_" . $post['phone'];
            $msg_id = Cache::get($cache_name);
            if (!$msg_id) {
                $this->apiReturn('400', '短信验证码错误');

            } else {
                $res = checkJsmsCode($msg_id, $post['code']);
                if ($res['http_code'] === 200) {
                    Cache::rm($cache_name);
                    $this->apiReturn('200', '验证成功');
                } else {
                    $this->apiReturn('400', '短信验证码错误');
                }
            }
        }
    }
    /*
     * 更换手机号
     */
    public function update_phone()
    {
        //获取客户端传过来的信息
        $phone = input('phone','','trim');
        $code = input('code','','trim');
        $uid = input('uid','','trim');
        if(empty($phone) || empty($code) ||empty($uid)){
            return json(array('code'=>'400','msg'=>'信息不能为空'));
        }
        //查询手机号是否存在
        $res = Db::name('user')->where('phone',$phone)->find();
        if($res){
            $this->apiReturn('400', '手机号已经存在请确认');
        }
        //判断验证码是否正确
        $cache_name = "jsms_" . $phone;
        $msg_id = Cache::get($cache_name);
        if (!$msg_id) {
            $this->apiReturn('400', '短信验证码错误');

        } else {
            $res = checkJsmsCode($msg_id,$code);
            if ($res['http_code'] === 200) {
                Cache::rm($cache_name);
            } else {
                $this->apiReturn('400', '短信验证码错误');
            }
        }
        $update = Db::name('user')->where('uid',$uid)->setField('phone',$phone);
        if($update){
            $this->apiReturn('200', '修改成功');
        }else{
            $this->apiReturn('400', '修改失败');
        }
    }


    /**
     * 退出登录接口
     */
    public function logout(){
        if (Request::instance()->isPost()){
            $post = Request::instance()->post();
            $res = Db::name('user')
                ->where("uid",$post['uid'])
                ->setField("token",null);
            if ($res!==false){
                return json(array('code'=>"200",'msg'=>"退出成功"));
            }else{
                return json(array('code'=>"401",'msg'=>"退出失败"));
            }

        }
    }

    public function send()
    {
        if(Request::instance()->isPost()){
            $post = Request::instance()->post();
            $send = [
                '1'=>'龙门小猪'
            ];
            $res = sendJsmsMessage(1,174979,$send);
            var_dump($res);
        }
    }
}